//
//  ComposeViewController.swift
//  Weibo
//
//  Created by 孙国强 on 2017/7/4.
//  Copyright © 2017年 孙国强. All rights reserved.
//

import UIKit
import SVProgressHUD

class ComposeViewController: UIViewController {

    // MARK:- 懒加载属性
    fileprivate lazy var titleView : ComposeTitleView = ComposeTitleView()
    fileprivate lazy var images : [UIImage] = [UIImage]()
    fileprivate lazy var emoticonVC : EmoticonController = EmoticonController {[weak self] (emoticon) in
        self?.textView.insertEmoticon(emoticon: emoticon)
        self?.textViewDidChange(self!.textView)
    }
    
    // MARK:- 控件属性
    @IBOutlet weak var textView: ComposeTextView!
    @IBOutlet weak var picPickerView: PicPickerCollectionView!
    
    // MARK:- 约束属性
    @IBOutlet weak var toolBarBottomCons: NSLayoutConstraint!
    @IBOutlet weak var picPickerViewHCons: NSLayoutConstraint!
    
    override func viewDidLoad() {
        super.viewDidLoad()

        setupNavigationBar()
        
        // 监听通知
        NotificationCenter.default.addObserver(self, selector: #selector(ComposeViewController.KeyboardWillChangeFrame(note:)), name: NSNotification.Name.UIKeyboardWillChangeFrame, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(ComposeViewController.addPhotoClick), name: Notification.Name(rawValue: PicPickerAddPhotoNote), object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(ComposeViewController.removePhotoClick(note:)), name: NSNotification.Name(PicPickerRemovePhotoNote), object: nil)
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        textView.becomeFirstResponder()
    }
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    
}

// MARK:- 设置UI界面
extension ComposeViewController {
    fileprivate func setupNavigationBar() {
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .plain, target: self, action: #selector(ComposeViewController.closeItemClick))
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发送", style: .plain, target: self, action: #selector(ComposeViewController.sendItemClick))
//            )
        navigationItem.rightBarButtonItem?.isEnabled = false
        
        titleView.frame = CGRect(x: 0, y: 0, width: 100, height: 40)
        navigationItem.titleView = titleView
    }
}

// MARK:- 添加照片和删除照片的事件
extension ComposeViewController {
    @objc fileprivate func addPhotoClick() {
        // 1.判断数据源是否可用
        if !UIImagePickerController.isSourceTypeAvailable(.photoLibrary) {
            return
        }
        
        // 2.创建照片选择控制器
        let ipc = UIImagePickerController()
        
        // 3.设置照片源
        ipc.sourceType = .photoLibrary
        
        
        // 4.设置代理
        ipc.delegate = self
        
        // 5.弹出选择照片的控制器
        present(ipc, animated: true, completion: nil)
    }
    
    @objc fileprivate func removePhotoClick(note : Notification) {
        guard let image = note.object as? UIImage else {
            return
        }
        
        guard let index = images.index(of: image) else {
            return
        }
        
        images.remove(at: index)
        
        picPickerView.images = images
    }
}

// MARK:- UIImagePickerController的代理方法
extension ComposeViewController : UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        print(info)
        let image = info[UIImagePickerControllerOriginalImage] as! UIImage
        
        images.append(image)
        
        picPickerView.images = images
        
        picker.dismiss(animated: true, completion: nil)
    }
}

// MARK:- 事件监听函数
extension ComposeViewController {
    @objc fileprivate func closeItemClick() {
        textView.resignFirstResponder()
        dismiss(animated: true, completion: nil)
    }
    
    @objc fileprivate func sendItemClick() {
        textView.resignFirstResponder()
        
        let statusText = textView.getEmoticonString()
        
        // 定义回调的闭包
        let finishedCallBack = { (_ isSuccess : Bool) -> () in
            if !isSuccess {
                SVProgressHUD.showError(withStatus: "发送微博失败")
                return
            }
            SVProgressHUD.show(withStatus: "发送微博成功")
            self.dismiss(animated: true, completion: nil)
        }
        
        // 获取用户选中的图片
        if let image = images.first {
            NetworkTools.shareInstance.sendStatus(statusText: statusText, image: image, isSuccess: finishedCallBack)
        } else {
            NetworkTools.shareInstance.sendStatus(statusText: statusText, isSuccess: finishedCallBack)
        }
    }
    
    @objc fileprivate func KeyboardWillChangeFrame(note : NSNotification) {
        let duration = note.userInfo![UIKeyboardAnimationDurationUserInfoKey] as! TimeInterval
        
        let endFrame = (note.userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue).cgRectValue
        let y = endFrame.origin.y
        
        let margin = UIScreen.main.bounds.height - y
        
        
        UIView.animate(withDuration: duration) {
            self.toolBarBottomCons.constant = margin
        }
    }
    
    @IBAction func picPickerBtnClick(_ sender: UIButton) {
        textView.resignFirstResponder()
        
        UIView.animate(withDuration: 0.5) { 
            self.picPickerViewHCons.constant = UIScreen.main.bounds.height * 0.65
        }
    }
    
    @IBAction func emoticonBtnClick(_ sender: Any) {
        textView.resignFirstResponder()
        
        textView.inputView = textView.inputView != nil ? nil : emoticonVC.view
        
        textView.becomeFirstResponder()
    }
}

// MARK:- UITextView的代理方法
extension ComposeViewController : UITextViewDelegate {
    func textViewDidChange(_ textView: UITextView) {
        self.textView.placeHolderLabel.isHidden = textView.hasText
        navigationItem.rightBarButtonItem?.isEnabled = textView.hasText
    }
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        textView.resignFirstResponder()
    }
}

